package com.t.bricks.bussiness.controller.tts;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.t.bricks.bussiness.service.tts.TextToSoundService;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;

@RestController
@RequestMapping("/tts/")
@Api(value="文字转语音", tags={"文字转语音操作接口"})
public class TidingsController {
	
	@Autowired
	private TextToSoundService textToSoundService;
	
	/**
	 * 把文字内容转换成mp3格式音频
	 * @param text 待转换文字
	 * @return
	 */
	//[start]
	@ApiOperation(value="把文字内容转换成mp3格式音频")
	@ApiImplicitParams({
		@ApiImplicitParam(name="text", value="待转换文字", dataType="String", paramType="query", required=true)
	})
	@ApiResponses({
		@ApiResponse(code=200, message="{\"success\": 布尔值, \"msg\": 文字提示, \"data\": 码值/令牌}"),
		@ApiResponse(code=400, message="错误的请求,请检查路径"),
		@ApiResponse(code=404, message="请求路径没有或页面跳转路径不对"),
		@ApiResponse(code=1000001, message="内部请求密钥错误"),
		@ApiResponse(code=1000002, message="您还没有登录或登录已超时,需要重新登录"),
		@ApiResponse(code=1000003, message="检查登录状态失败,请稍后重试！"),
		@ApiResponse(code=1000004, message="请求的操作不存在,请检查访问地址正确性,如大小写"),
		@ApiResponse(code=1000005, message="响应后在系统内部发生不可预知的错误"),
		@ApiResponse(code=1019000, message="1019000~1999999为拦截器调用方法错误"),
		@ApiResponse(code=8101, message="内容为空"),
		@ApiResponse(code=8102, message="生成语音失败"),
		@ApiResponse(code=8103, message="音频压缩失败")
	})
	//http://localhost:9004/tts/create/mp3?sInsideKey=123456&text=This%20is%20a%20pen!%20这是我的测试,物理内存至少需要512MB，建议2GB以上,虚拟内存是主机物理内存的两倍
	//[end]
	@RequestMapping(method={RequestMethod.GET}, value="/create/mp3")
	public MsgEmity toMp3(String text) {
		return textToSoundService.toMp3(text);
	}
	
	/**
	 * 取音频文件
	 * @param httpSession
	 * @param model
	 */
	//[start]
	@ApiOperation(value="把文字内容转换成mp3格式音频")
	@ApiImplicitParams({
		@ApiImplicitParam(name="text", value="待转换文字", dataType="String", paramType="query", required=true)
	})
	@ApiResponses({
		@ApiResponse(code=200, message="{\"success\": 布尔值, \"msg\": 文字提示, \"data\": 码值/令牌}"),
		@ApiResponse(code=400, message="错误的请求,请检查路径"),
		@ApiResponse(code=404, message="请求路径没有或页面跳转路径不对"),
		@ApiResponse(code=1000001, message="内部请求密钥错误"),
		@ApiResponse(code=1000002, message="您还没有登录或登录已超时,需要重新登录"),
		@ApiResponse(code=1000003, message="检查登录状态失败,请稍后重试！"),
		@ApiResponse(code=1000004, message="请求的操作不存在,请检查访问地址正确性,如大小写"),
		@ApiResponse(code=1000005, message="响应后在系统内部发生不可预知的错误"),
		@ApiResponse(code=1019000, message="1019000~1999999为拦截器调用方法错误"),
		@ApiResponse(code=8101, message="内容为空"),
		@ApiResponse(code=8102, message="生成语音失败"),
		@ApiResponse(code=8103, message="音频压缩失败")
	})
	//http://localhost:9004/tts/play/mp3?sInsideKey=123456&text=This%20is%20a%20pen!%20这是我的测试,物理内存至少需要512MB，建议2GB以上,虚拟内存是主机物理内存的两倍
	//[end]
	@RequestMapping(method={RequestMethod.GET}, value="/play/mp3")
	public void downloadMp3(HttpServletRequest request, HttpServletResponse response,
			String text) {
		MsgEmity me = textToSoundService.toMp3(text);
		if (!me.isSuccess()) {
			return;
		}
		
		String fileNameAndPath = me.getMsg();

		File downloadFile = new File(fileNameAndPath);//读文件"D:/kkkk.mp3";

		ServletContext context = request.getServletContext();

		// get MIME type of the file
		String mimeType = context.getMimeType(fileNameAndPath);
		if (mimeType == null) {
			// set to binary type if MIME mapping not found
			mimeType = "application/octet-stream";
		}

		// set content attributes for the response
		response.setContentType(mimeType);
		response.setContentLength((int) downloadFile.length());

		// set headers for the response
		String downLoadName = downloadFile.getName();
		try {//转换编码防止中文名文件下载名乱码问题
			downLoadName = new String(downloadFile.getName().getBytes("UTF-8"), "iso8859-1");
		} catch (UnsupportedEncodingException e) {
			Log.error("转换编码异常:", e.getMessage());
		}
		String headerValue = String.format("attachment; filename=\"%s\"", downLoadName);
		response.setHeader("Content-Disposition", headerValue);

		try(InputStream myStream = new FileInputStream(fileNameAndPath);) {
			IOUtils.copy(myStream, response.getOutputStream());//复制文件内容
			response.flushBuffer();
			myStream.close();//关闭文件
		} catch (Exception e) {
			Log.error("读取音频文件异常:", e.getMessage());
		}
	}
	
}
